<template>
<!--    水平和垂直居中-->
    <el-row class="login-container" justify="center" align="middle">
        <el-card style="max-width: 480px">
            <template #header>
                <div class="card-header">

                    <img :src="imgUrl" />
                </div>
            </template>
            <div style="text-align: center">
                <span><b>欢迎使用DIDI陪诊系统</b> </span>
            </div>

            <div class="jump-link">
                <el-link type="primary" @click="handleChange">
                    {{ formType ? '返回登陆': '注册账号' }}
                </el-link>
            </div>
            <el-form ref="loginFormRef"
                    :model="loginForm"
                style="max-width: 600px"
                     :rules="rules"
            >
                <el-form-item prop="userName">
                    <el-input  v-model="loginForm.userName" placeholder="手机号" prefix-icon="UserFilled" />
                </el-form-item>
                <el-form-item prop="passWord">
                    <el-input v-model="loginForm.passWord" placeholder="密码" prefix-icon="Lock" type="password" show-password />
                </el-form-item>
                <!--  注册页面存在 -->
                <el-form-item v-if="formType" prop="validCode">
                    <el-input v-model="loginForm.validCode" placeholder="验证码" >
                        <template #append>
                            <span @click="countDownChange">{{ countdown.validText }}</span>
                        </template>
                    </el-input>

                </el-form-item>
                <!--提交按钮-->
                <el-form-item>
                    <el-button type="primary" :style="{ width:'100%'}" @click="submitForm(loginFormRef)" >
                        {{ formType ? '注册': '登录' }}
                    </el-button>
                </el-form-item>


            </el-form>
        </el-card>
    </el-row>
</template>
<script setup>
import { ref, reactive, computed ,toRaw } from 'vue'
import { getCode, login, getMenuList } from '../../api'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const store = useStore();
const imgUrl = new URL('../../../public/images/login-head.png',import.meta.url).href;
// 切换表单(0注册 1登陆)
const formType = ref(0);
const router = useRouter();

const routerList = computed(()=> store.state.menu.routerList);

// 表单示例
const loginFormRef = ref()
// 表单数据
const loginForm = reactive({
    userName: '',
    passWord: '',
    validCode: ''
});
// 切换登陆/注册
const handleChange = () => {
    formType.value = formType.value ? 0 : 1
};
// 发送短信
const countdown = reactive({
    validText: '发送验证码',
    time: 60
});
let flag = false;
// 倒计时
const countDownChange = () => {
    if (flag) {
        return ElMessage({
            message: '请稍等',
            type: 'error'
        })

    }

    // 判断手机号是否正确
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    if(!loginForm.userName || !phoneReg.test(loginForm.userName) ){
        return ElMessage({
            message: '请检查手机号是否正确',
            type: 'warning'
        })
    }

    const timer = setInterval(
        () =>{
            if (countdown.time <= 0 ){
                countdown.time = 60;
                countdown.validText = '发送验证码';
                flag = false;
                // 清除定时器
                clearInterval(timer);
            }else{

                countdown.time -= 1;
                countdown.validText = `剩余${countdown.time}`
            }

        },1000
    );
    flag = true;

    // 发送请求
    getCode({ phone : loginForm.userName}).then(({data}) => {
        console.log(data,{data});
        if (data.code === '0' ){
            ElMessage.success('发送成功！');
        }
    })

}

// 用户名校验
const validateUsername = (rule,value,callback) => {
    if(value === ''){
        callback(new Error('请输入账号'));
    }
    callback();
};

// 密码校验
const validatePassword = (rule,value,callback) => {
    if(value === ''){
        callback(new Error('请输入密码'));
    }
    callback();
};
// 表单校验 blur失去焦点时触发
const rules = reactive({
    userName: [{ validator : validateUsername, trigger: 'blur'}],
    passWord: [{ validator : validatePassword, trigger: 'blur'}]
});


const submitForm = async(formEl) => {
    if(!formEl){
        return;
    }
    await formEl.validate((valid, fields) => {
        if(valid){
            // 校验成功！

            // 注册页面
            if(formType.value){
                ElMessage.success('发送注册请求！');
            }
            else {
                // 登陆页面

                // 发送请求
                login({
                        username : loginForm.userName,
                        password : loginForm.passWord
                    }
                ).then(({data}) => {
                    if (data.code === 0){
                        ElMessage.success('登陆成功！');
                        //console.log('token is saved', data.data.token);
                        // 缓存token
                        localStorage.setItem('pz_token',data.data.token);

                        // todo: 调用获取用户信息接口，并且保存在localStorage

                        // 获取菜单
                        // getMenuList().then(({ data }) =>{
                        //
                        //
                        //     store.commit('dynamicMenu',data.data);
                        //     console.log(routerList.value, 'routerList');
                        //
                        // });

                        router.push('/');
                    }else {
                        ElMessage.error( data.msg);
                    }
                })
            }


        }else{
            console.log('error',fields);
        }
    })
}

</script>
<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 0
}
.login-container {
    height: 100%;
    .card-header{
        background-color: #899fe1;
        img {
            width: 430px;
        }
    }
    .jump-link {
        /* 位置靠右 */
        text-align: right;
        margin-bottom: 10px;
    }
}
</style>
